package com.lanou3g.Code0523.permission;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/5/23;
 * Otherwise, I don't know who created it either
 */

@WebFilter(filterName = "UserFilter"
        ,urlPatterns = {"/user/*","*.mp3"})
public class UserFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            // 已经登陆过,可以放行
            chain.doFilter(req, resp);
        } else {
            // 没登录 不放行,重定向到login.html
            response.sendRedirect("/login.html");
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
